import * as Sentry from '@sentry/vue'
import { BrowserTracing } from '@sentry/tracing'
import router from '@/router'
import store from '@/store'

// 性能指标监控
const performanceMonitor = {
  // 页面加载时间
  pageLoadTime: () => {
    const timing = window.performance.timing
    return timing.loadEventEnd - timing.navigationStart
  },
  
  // 首次内容绘制时间
  firstPaintTime: () => {
    const paint = window.performance.getEntriesByType('paint')
    return paint[0] ? paint[0].startTime : 0
  },
  
  // API请求监控
  apiResponseTime: (startTime, endTime) => {
    return endTime - startTime
  },

  // 内存使用监控
  memoryUsage: () => {
    if (window.performance && window.performance.memory) {
      return {
        usedJSHeapSize: window.performance.memory.usedJSHeapSize,
        totalJSHeapSize: window.performance.memory.totalJSHeapSize
      }
    }
    return null
  },

  // 资源加载监控
  resourceTiming: () => {
    const resources = window.performance.getEntriesByType('resource')
    return resources.map(resource => ({
      name: resource.name,
      duration: resource.duration,
      type: resource.initiatorType
    }))
  }
}

// 业务监控指标
const businessMonitor = {
  // 用户行为跟踪
  trackUserAction: (action, category, label) => {
    Sentry.addBreadcrumb({
      category,
      message: `User Action: ${action}`,
      level: 'info',
      data: { label }
    })
  },
  
  // 错误上报
  reportError: (error, context) => {
    Sentry.captureException(error, {
      extra: context
    })
  },

  // 用户会话跟踪
  trackUserSession: () => {
    const user = store.state.user // 假设用户信息存储在Vuex中
    if (user) {
      Sentry.setUser({
        id: user.id,
        username: user.username,
        email: user.email
      })
    }
  },

  // 自定义业务指标
  trackBusinessMetric: (metricName, value, tags = {}) => {
    Sentry.addBreadcrumb({
      category: 'business-metric',
      message: `Metric: ${metricName}`,
      level: 'info',
      data: { value, ...tags }
    })
  }
}

// 初始化Sentry
export const initMonitor = (Vue, app) => {
  Sentry.init({
    app,
    dsn: process.env.VUE_APP_SENTRY_DSN, // 从环境变量获取DSN
    integrations: [
      new BrowserTracing({
        routingInstrumentation: Sentry.vueRouterInstrumentation(router),
        tracingOrigins: ['localhost', window.location.hostname],
        tracesSampleRate: 1.0
      })
    ],
    environment: process.env.NODE_ENV,
    release: process.env.VUE_APP_VERSION || '1.0.0',
    beforeSend(event) {
      // 可以在这里过滤或修改事件
      return event
    },
    // 启用性能监控
    tracesSampleRate: 1.0,
    // 启用会话重放
    replaysSessionSampleRate: 0.1,
    replaysOnErrorSampleRate: 1.0
  })
  
  // 全局错误处理
  Vue.config.errorHandler = (error, vm, info) => {
    businessMonitor.reportError(error, {
      info,
      componentName: vm.$options.name,
      propsData: vm.$options.propsData,
      route: router.currentRoute.fullPath
    })
  }

  // 路由变化监控
  router.beforeEach((to, from, next) => {
    businessMonitor.trackUserAction('route-change', 'navigation', {
      from: from.fullPath,
      to: to.fullPath
    })
    next()
  })

  // 定期收集性能指标
  setInterval(() => {
    const metrics = {
      memory: performanceMonitor.memoryUsage(),
      resources: performanceMonitor.resourceTiming()
    }
    businessMonitor.trackBusinessMetric('performance', metrics)
  }, 60000) // 每分钟收集一次
}

export { performanceMonitor, businessMonitor } 